package com.cat.binaryTree;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/reverse-nodes-in-even-length-groups/
 * @create 2025/9/26 16:28
 * @since JDK17
 */

public class Solution66 {
    public ListNode reverseEvenLengthGroups(ListNode head) {
        ListNode p0 = null, cur = head, next, pre = null;
        for (int i = 1, j, k = 1, cnt; cur != null; k++, i++) {
            ListNode t = cur;
            for (cnt = 0; cnt < k && t != null; cnt++, pre = t, t = t.next);
            if (cnt % 2 != 0) { // 不需要翻转
                cur = t;
                p0 = pre;
            } else {
                for (j = 0; j < cnt; j++) {
                    next = cur.next;
                    cur.next = pre;
                    pre = cur;
                    cur = next;
                }
                next = p0.next;
                p0.next.next = cur;
                p0.next = pre;
                p0 = next;
            }
        }

        return head;
    }
}
